package com.dis.user.controller.admin;

import com.dis.common.annotation.CheckPermission;
import com.dis.common.constant.JwtClaimsConstant;
import com.dis.common.exception.AccountNotFoundException;
import com.dis.common.result.PageResult;
import com.dis.common.result.Result;
import com.dis.common.utils.JwtTool;
import com.dis.common.utils.JwtUtil;
import com.dis.pojo.dto.UserDTO;
import com.dis.pojo.dto.UserLoginDTO;
import com.dis.pojo.dto.UserPageQueryDTO;
import com.dis.pojo.entity.User;
import com.dis.pojo.vo.UserLoginVO;

import com.dis.user.properties.JwtProperties;
import com.dis.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * 员工管理
 */
@RestController
@RequestMapping("/admin/user")
@Api(tags = "用户相关接口")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired(required = false)
    private JwtTool jwtTool; // 注入网关的JwtTool，可能为null

    /**
     * 登录
     * @param
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("用户登录")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户登录：{}", userLoginDTO);
        
        try {
            User user = userService.login(userLoginDTO);

            // 登录成功后，生成jwt令牌
            String token;
            if (jwtTool != null) {
                // 优先使用网关的JwtTool生成JWT（RS256算法）
                log.info("使用JwtTool生成令牌");
                token = jwtTool.createToken(user.getId(), Duration.ofMillis(jwtProperties.getAdminTtl()));
            } else {
                // 回退到原来的方式（HS256算法）
                log.info("使用JwtUtil生成令牌");
                Map<String, Object> claims = new HashMap<>();
                claims.put(JwtClaimsConstant.USER_ID, user.getId());
                token = JwtUtil.createJWT(
                        jwtProperties.getAdminSecretKey(),
                        jwtProperties.getAdminTtl(),
                        claims);
            }

            UserLoginVO employeeLoginVO = UserLoginVO.builder()
                    .id(user.getId())
                    .userName(user.getUsername())
                    .name(user.getName())
                    .token(token)
                    .build();

            return Result.success(employeeLoginVO);
        } catch (AccountNotFoundException e) {
            log.error("登录失败：账号不存在, {}", userLoginDTO.getUsername(), e);
            return Result.error("账号不存在，请检查用户名");
        } catch (Exception e) {
            log.error("登录失败：系统异常, {}", userLoginDTO.getUsername(), e);
            return Result.error("登录失败，系统异常");
        }
    }

    /**
     * 退出
     * @return
     */
    @PostMapping("/logout")
    @ApiOperation("员工退出登录")
    public Result<String> logout() {
        return Result.success();
    }


    /**
     * 添加员工
     * @param userDTO
     * @return
     */
    @PostMapping
    @ApiOperation("新增员工")
    @CheckPermission("user:add")
    public Result save(@RequestBody UserDTO userDTO){
        log.info("新增员工");
        System.out.println("当前线程的id为:" + Thread.currentThread().getId());
        userService.save(userDTO);
        return Result.success();
    }

    /**
     * 员工分页
     * @param userPageQueryDTO
     * @return
     */
    @GetMapping("/page")
    @ApiOperation("员工分页查询")
    @CheckPermission("user:query")
    public Result<PageResult> page(UserPageQueryDTO userPageQueryDTO){
        log.info("员工分页查询，传递过来的参数为：{}", userPageQueryDTO);
        PageResult pageResult = userService.pageQuery(userPageQueryDTO);
        return Result.success(pageResult);
    }

    /**
     * 启用禁用员工账号
     * @param status
     * @param id
     * @return
     */
    @PostMapping("/status/{status}")
    @ApiOperation("启用禁用员工账号")
    @CheckPermission("user:status")
    public Result startOrStop(@PathVariable Integer status,Long id){
        log.info("启用禁用员工账号：{},{}",status,id);
        userService.startOrStop(status,id);
        return Result.success();
    }

    /**
     * 根据id查询员工
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation("根据id查询员工")
    @CheckPermission("user:query")
    public Result<User> getById(@PathVariable Long id){
        User user = userService.getById(id);
        return Result.success(user);
    }

    /**
     * 编辑员工信息
     * @param userDTO
     * @return
     */
    @PutMapping
    @ApiOperation("编辑员工信息")
    @CheckPermission("user:edit")
    public Result update(@RequestBody UserDTO userDTO){
        log.info("编辑员工信息：{}", userDTO);
        userService.update(userDTO);
        return Result.success();
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @ApiOperation("删除用户")
    @CheckPermission("user:delete")
    public Result delete(@PathVariable Integer id){
        userService.deleteUser(id);
        return Result.success();
    }

}
